package com.lagou.filter;

import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.*;
import java.util.concurrent.*;

@Activate(group = {Constants.CONSUMER})
public class MonitorFilter implements Filter , Runnable {

    private Map<String, ArrayList<Long>> methodTimeMap = new ConcurrentHashMap<>();

    public MonitorFilter() {
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(this,1,5, TimeUnit.SECONDS);
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        long endTime = System.currentTimeMillis();
        long time = endTime - startTime;
        String methodName = invocation.getMethodName();
        ArrayList<Long> list = methodTimeMap.get(methodName);
        if (list == null) {
            list = new ArrayList<>();
            methodTimeMap.put(methodName, list);
        }
        list.add(time);
        return result;
    }

    @Override
    public void run() {
        System.out.println("\n\n");
        Iterator<String> iterator = methodTimeMap.keySet().iterator();
        while (iterator.hasNext()) {
            String methodName = iterator.next();
            ArrayList<Long> list = methodTimeMap.get(methodName);
            ArrayList<Long> tempList = new ArrayList<>(list);
            list.clear();
            Collections.sort(tempList);
            int tp90Index = (int) (tempList.size() * 0.9);
            int tp99Index = (int) (tempList.size() * 0.99);
            long tp90 = tempList.get(tp90Index);
            long tp99 = tempList.get(tp99Index);
            //System.out.println(tempList);
            System.out.println(methodName + "调用次数:"+tempList.size()+",\t\tTP90指标为："+tp90+",\t\tTP99指标为："+tp99);
        }

    }
}
